<template>
  <div ref="wrapperRef" class="icon-block">
    <a-trigger
      v-model:popup-visible="visible"
      trigger="click"
      position="bl"
      :unmount-on-close="false"
      @popup-visible-change="popupVisibleChange"
    >
      <a-input v-model="inputValue" placeholder="点击选择图标">
        <template #prefix>
          <component
            :is="modelValue"
            :size="28"
            :stroke-width="2"
          />
        </template>
      </a-input>
      <template #content>
        <a-scrollbar style="height: 200px; overflow-y: auto;">
          <div
            v-if="visible"
            ref="iconListRef"
            class="icon-list-wrapper"
            :style="listStyle"
          >
            <div
              v-for="(item, index) in iconNames"
              :key="index"
              class="icon-item"
              @click="clickIcon(item)"
            >
              <component
                :is="item"
                :size="34"
                :stroke-width="2"
              />
            </div>
          </div>
        </a-scrollbar>
      </template>
    </a-trigger>
  </div>
</template>

<script setup lang="ts">
import { ref, toRef, computed } from 'vue';
import GlobalComponents from '@arco-design/web-vue/es/icon';

const props = defineProps({
  modelValue: {
    type: String,
    require: false,
    default: 'IconList'
  }
});

const emit = defineEmits(['update:modelValue']);

const iconNames = computed(() => {
  const result: any[] = [];
  Object.keys(GlobalComponents).forEach(key => {
    const item = GlobalComponents[key];
    if (item.name && item.name !== 'install') {
      result.push(item.name);
    }
  });
  return result;
});
const listWidth = ref(323);
const listStyle = computed(() => {
  return {
    width: `${listWidth.value}px`
  };
});

const visible = ref(false);
const inputValue = toRef(props, 'modelValue');
const wrapperRef = ref();
const iconListRef = ref();

const clickIcon = (iconName: string) => {
  emit('update:modelValue', iconName);
  visible.value = false;
};

const popupVisibleChange = (value: boolean) => {
  if (value) {
    listWidth.value = wrapperRef.value.offsetWidth;
  }
};
</script>

<style scoped lang="less">
.icon-block {
  width: 100%;
  position: relative;
}

.icon-list-wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
  border: 1px solid var(--color-neutral-3);
  background-color: #FFF;
}

.icon-item {
  margin: 2px;
  width: 36px;
  height: 36px;
  text-align: center;
  color: #3d3d3f;
  border: 1px solid #EFEFEF;
  background-color: #FFF;
}

.icon-item:hover {
  background-color: #E2E2E2;
}
</style>
